package dao

import (
	"errors"
	"strconv"
	"time"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/devices"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
)

// -------------------- dao层 - 设备相关操作 -----------------------//

type DeviceDiscountsDao struct {
}

func NewDeviceDiscountsDao() *DeviceDiscountsDao {
	return &DeviceDiscountsDao{}
}

// DrawDeviceDiscountsRecord 设备优惠
func (d *DeviceDiscountsDao) DrawDeviceDiscountsRecord(param request.DrawDeviceDiscountsReq) *dingo.ErrorWrap {
	ddrInfo := d.GetDrawDeviceDiscountsRecord(param).Unwrap().(*devices.DrawDeviceDiscountsRecordModel)
	if ddrInfo.ID > 0 && (ddrInfo.DeviceSn != param["deviceSn"] || param["restartPwd"] != "YES") {
		return dingo.ErrorIf(errors.New("今日已领取优惠"))
	}

	if param["restartPwd"] == "YES" {
		return dingo.ErrorIf(nil)
	}

	var typeNum, _ = strconv.Atoi(param["type"])
	dbInfo := &devices.DrawDeviceDiscountsRecordDb{
		Uuid:     param["uuid"],
		WxOpenid: param["openId"],
		DeviceSn: param["deviceSn"],
		Type:     uint8(typeNum),
		Status:   3,
	}
	db := global.Orm.Create(dbInfo)

	return dingo.ErrorIf(db.Error, dbInfo)
}

func (d *DeviceDiscountsDao) GetDrawDeviceDiscountsRecord(param request.DrawDeviceDiscountsReq) *dingo.ErrorWrap {
	dbInfo := &devices.DrawDeviceDiscountsRecordModel{}

	nowDate := time.Now().Format("2006-01-02")
	where := "uuid=? AND status<>? AND DATE_FORMAT(create_time, '%Y-%m-%d')=?"
	db := global.Orm.Where(where, param["uuid"], 1, nowDate)
	db.Find(&dbInfo)

	return dingo.ErrorIf(db.Error, dbInfo)
}

func (d *DeviceDiscountsDao) GetDrawDeviceDiscountsRecordByUuid(uuid, typeNum string) *devices.DrawDeviceDiscountsRecordModel {
	dbInfo := &devices.DrawDeviceDiscountsRecordModel{}
	db := global.Orm.Where("uuid=?", uuid)

	if typeNum != "" {
		db.Where("type=?", typeNum)
	}

	db.Find(&dbInfo)

	return dbInfo
}
